package kg.aibek.projecteuler.p51;

import java.util.HashMap;
import java.util.Map;

import kg.aibek.preuler1.Util;

public class Problem51 {
	public void solve() {
		int d = 1000;
		while (true) {
			if (!Util.isPrime(++d))
				continue;

			String str = d + "";
			if (primeCount(str, max(str)) == 8) {
				System.out.println(d);
				break;
			}
		}
	}

	private int primeCount(String str, int[] par) {
		if (par[1] < 2)
			return 0;

		char ch = (char) par[0];
		int ind[] = new int[par[1]];

		int j = 0;
		for (int i = 0; i < str.length(); i++) {
			if (ch == str.charAt(i))
				ind[j++] = i;
		}

		StringBuilder sb = new StringBuilder();
		sb.append(str);

		int count = 0;
		for (int i = 0; i < 10; i++) {
			for (int k = 0; k < ind.length; k++) {
				sb.replace(ind[k], ind[k] + 1, i + "");
			}
			int d = Integer.parseInt(sb.toString());
			if (d < Math.pow(10, sb.length() - 1))
				continue;
			if (Util.isPrime(d)) {
				count++;
			}
		}
		return count;
	}

	private int[] max(String str) {
		Map<Character, Integer> map = new HashMap<Character, Integer>();

		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if (map.containsKey(ch)) {
				map.put(ch, map.get(ch) + 1);
			} else {
				map.put(ch, 1);
			}
		}

		char mch = str.charAt(0);
		int count = 1;
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if (count < map.get(ch)) {
				mch = ch;
				count = map.get(ch);
			}
		}

		return new int[] { mch, count };
	}

	public static void main(String[] args) {
		Problem51 p = new Problem51();
		p.solve();
	}
}
